package org.fastsyncer.rest.interceptor;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.fastsyncer.common.constant.CommonConstant;
import org.fastsyncer.common.util.ApplicationUtil;

public class WebServiceInterceptor extends AbstractPhaseInterceptor<Message> {

	private final static Logger LOG = LogManager.getLogger(WebServiceInterceptor.class);

	private final static List<String> IPS = new ArrayList<String>();
	
	static {
		String ips = ApplicationUtil.getKey(CommonConstant.REST_APPROVAL_IP);
		String[] split = ips.split(",");
		for (String ip : split) {
			IPS.add(ip);
		}
	}
	
	public WebServiceInterceptor() {
		super(Phase.RECEIVE);
	}

	public void handleMessage(Message message) throws Fault {
		// 指定CXF获取客户端的HttpServletRequest : http-request；
		HttpServletRequest request = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST);
		String ipAddress = "";
		if (null != request) {
			 // 取客户端IP地址
			ipAddress = getUserIpAddr(request);
			if (IPS.contains(ipAddress)) {
				return;
			}
		}
		LOG.error("IP address " + ipAddress + " 无权限!");
		throw new Fault(new IllegalAccessException("IP address " + ipAddress + " 无权限!"));
	}

	/**
	 * 获取IP地址的方法
	 * 
	 * @param request
	 * @return
	 */
	private String getUserIpAddr(HttpServletRequest request) {
		// 获取经过代理的客户端的IP地址; 排除了request.getRemoteAddr() 方法
		// 在通过了Apache,Squid等反向代理软件就不能获取到客户端的真实IP地址了
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (ip != null && ip.indexOf(",") > 0) {
			String[] arr = ip.split(",");
			// 有多个ip时取最后一个ip
			ip = arr[arr.length - 1].trim();
		}
		return ip;
	}

}